/*
 * @Author: Zhang Kai
 * @Date: 2022-05-17 11:11:45
 * @LastEditors: mayijun
 * @LastEditTime: 2022-07-14 11:16:26
 * @FilePath: /metricsx-standard-ui/src/components/Bulk/index.tsx
 */

import { defineComponent, ref, watch } from 'vue';

import API from '@/services';
import './index.scss';
import { Download, Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus/lib/index';
import { ElUpload } from 'element-plus/lib/index';
import ImportTipVue from '../downloadUploadBtns/importTip.vue';
import { downLoadFile } from '@/utils/http';

const Bulk = defineComponent({
  name: 'Bulk',
  props: {
    ...ElUpload.props,
    /* 下载模版list */
    downloadList: {
      type: Array,
      default: () => [{ command: 'text', text: '模版名称' }]
    },
    /* 限制文件类型list */
    fileTypeList: {
      type: Array,
      default: () => ['xlsx']
    },
    /* 下载Api */
    downloadUrl: {
      type: String,
      default: () => ''
    },
    /** 模板类型
     * 1-原子指标
     * 2-修饰词
     * 3-维度
     * 4-统计粒度
     * 5-主题
     * 6-派生指标
     */
    tmpCode: {
      type: String,
      default: '',
      require: true
    }
  },
  setup(props, { slots, attrs, emit }) {
    const visible = ref(false);

    const fileData: any = ref(null);

    const showImportResult = ref(false);

    /* 导出成功弹窗信息 */
    const importTip: any = ref();

    const uploadRef = ref();

    //指标导入
    const codeRef = ref();

    const httpRequest = ({ file }: any) => {
      const { fileTypeList } = props;
      /* 限制文件类型 */
      const fileType = file.name
        .substring(file.name.lastIndexOf('.') + 1)
        .toLowerCase();
      console.log(fileType, 'fileType');
      if (!fileTypeList.includes(fileType)) {
        ElMessage.error('文件格式错误,只支持xlsx文件');
        //错误时清空文件列表
        uploadRef.value.clearFiles();
        return;
      }
      /* 限制文件大小 */
      const fileSize = file.size / 1024 / 1024 < 100;
      if (!fileSize) {
        ElMessage.error(`文件大小超出100M`);
        //错误时清空文件列表
        uploadRef.value.clearFiles();
        return;
      }

      if (props?.tmpCode == '') {
        if (file.name.indexOf('原子') != -1) {
          codeRef.value = 1;
        } else if (file.name.indexOf('派生') != -1) {
          codeRef.value = 6;
        } else if (file.name.indexOf('主题') != -1) {
          codeRef.value = 5;
        } else {
          ElMessage.error('文件名称错误,只支持原子指标、派生指标和主题');
          //错误时清空文件列表
          uploadRef.value.clearFiles();
          return;
        }
      }
      const form: any = new FormData();
      form.append('uploadFile', file, file.name);
      fileData.value = form;
    };

    const submit = async () => {
      if (fileData.value == null) {
        ElMessage.error(`请先上传文件`);
        return false;
      }
      try {
        let { code, data }: any = await API.tmplate.postImportByTmpCode(
          {
            tmpCode: props?.tmpCode ? props?.tmpCode : codeRef.value
          },
          fileData.value
        );
        if (code === 200) {
          const { batchNo, duplicate, fail, success, total } = data;
          importTip.value = {
            batchNo,
            duplicate,
            fail,
            success,
            total
          };
          showImportResult.value = true;
          visible.value = false;
          uploadRef.value.clearFiles();
          emit('success');
        } else if (code === 500) {
          ElMessage.error('导入失败');
        }
      } catch (error) {}
    };

    const downloadFn = async () => {
      try {
        downLoadFile({
          url: `${props?.downloadUrl}${props?.tmpCode}`,
          method: 'get'
        });
      } catch (e) {
        console.log(e);
      }
    };

    watch(
      () => props?.downloadUrl,
      () => {
        downloadFn();
      }
    );
    return () => {
      const { downloadList } = props;
      return (
        <div class="Bulk">
          <el-button onClick={() => (visible.value = true)}>批量导入</el-button>
          <el-drawer
            custom-class="Bulk-drawer"
            close-on-click-modal={false}
            append-to-body={true}
            title="批量导入"
            v-model={visible.value}
            direction="rtl"
            lock-scroll={false}
            before-close={() => {
              uploadRef.value.clearFiles();
              visible.value = false;
            }}
          >
            <div class="file-title">
              <div class="file-title-text">选择文件</div>
              <el-dropdown
                trigger="click"
                onCommand={(code: any) => emit('command', code)}
                v-slots={{
                  dropdown: () => (
                    <el-dropdown-menu>
                      {downloadList?.map((v: any) => (
                        <el-dropdown-item {...v}>{v.text}</el-dropdown-item>
                      ))}
                    </el-dropdown-menu>
                  )
                }}
              >
                <el-button type="text">
                  <el-icon size={18}>
                    <Download />
                  </el-icon>
                  下载模版
                </el-button>
              </el-dropdown>
            </div>
            {visible.value ? (
              <el-upload
                class="upload-container"
                ref={uploadRef}
                drag
                multiple
                action="#"
                http-request={httpRequest}
                limit={1}
                show-file-list
                onRemove={(file: any) => {
                  //删除文件清空formdata
                  fileData.value = null;
                }}
                onExceed={(file: any) => {
                  file.length && ElMessage.warning('只限制一个文件');
                }}
              >
                <div class="el-upload__text">
                  <el-icon color="#396EFE" size={25}>
                    <Plus />
                  </el-icon>
                  <em>点击上传文件 或拖拽上传</em>
                  <div class="limit">Excel文件大小不能超过100M</div>
                </div>
              </el-upload>
            ) : undefined}

            <div class="footer-btn">
              <el-button type="primary" onClick={submit}>
                导入
              </el-button>
            </div>
          </el-drawer>

          {/* 导入成功弹窗 */}
          <ImportTipVue
            dialog-visible={showImportResult.value}
            onDlgClose={() => (showImportResult.value = false)}
            import-tip={importTip.value}
          />
        </div>
      );
    };
  }
});

export default Bulk;
